package com.topisv.tms.repository.qimen;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;

import com.topisv.tms.entity.qimen.DeliveryOrderTask;

public interface DeliveryOrderTaskDao extends PagingAndSortingRepository<DeliveryOrderTask, Long>, JpaSpecificationExecutor<DeliveryOrderTask> {

	/**
	 * 加载已锁定的数据
	 * @param ip
	 * @return List<DeliveryOrderTask>
	 */
	@Query("select t from DeliveryOrderTask t where dealIp = ?1 and dealStatus=1 and warehouseCode = ?2 and customerCode = ?3  and t.crTime between ?4 and ?5")
	List<DeliveryOrderTask> findTask(String ip, String warehouseCode, String customerCode, Date beforeDate, Date now);
	
	/**
	 * 加载已锁定的数据
	 * @param ip
	 * @return List<DeliveryOrderTask>
	 */
	@Query("select t from DeliveryOrderTask t where dealIp = ?1 and dealStatus=1 and warehouseCode = ?2 and t.crTime between ?3 and ?4 ")
	List<DeliveryOrderTask> findTask(String ip, String warehouseCode, Date beforeDate, Date now);
	
	
	/**
	 * 更新为已加载
	 * @param ip
	 * @param ids
	 * @return List<DeliveryOrderTask>
	 */
	@Modifying
	@Query("update DeliveryOrderTask t set t.dealStatus=2 where dealIp = ?1 and dealStatus=1 and id in ?2")
	void update(String ip,List<Long> ids);

	/**
	 * 根据客户订单号查找报文
	 *
	 * @param customerCode 客户编号
	 * @param customerOrderNo 客户订单号
	 * @param dealStatus 处理状态
	 * @return 报文集合
	 * @author <a href=mailto:yuanlianghe@nryuncang.com>yuanlianghe</a>
	 * @since 2016-10-25
	 */
	@Query("select new map(t.id as id, t.dealStatus as dealStatus) from DeliveryOrderTask t where t.customerCode=?1 and t.customerOrderNo=?2 order by t.id")
	List<Map<String, Object>> findByCustomerOrderNo(String customerCode, String customerOrderNo);
	
	/**
	 * 取消订单
	 *
	 * @param customerCode
	 * @param customerOrderNo
	 * @return [参数说明]
	 * @author <a href=mailto:yuanlianghe@nryuncang.com>yuanlianghe</a>
	 * @since 20161025
	 */
	@Modifying
	@Query("update DeliveryOrderTask t set t.dealStatus=?2 where t.id=?1 and t.dealStatus in ('0','1','2','3')")
	int cancel(Long id, String status);
	
	@Modifying
	@Query("update DeliveryOrderTask t set t.dealStatus=?2, t.dealTime=?3 where t.id=?1 and t.dealStatus in ('1','2','3','5')")
	int update(Long id, String status, Date dealTime);
	
	@Modifying
	@Query("update DeliveryOrderTask t set t.dealStatus=?3, t.dealTime=?4, t.dealCount=?5, t.dealIp=?2 where t.id=?1 and t.dealStatus<>'6'")
	int update(Long id, String dealIp, String dealStatus, Date dealTime, int dealCount);
}
